package com.shanjupay.common.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * @author hmk
 *
 * 七牛云存储服务的字节数组文件上传
 *
 **/
public class QiniuUtils {

    //日志对象
    public static  final Logger LOGGER = LoggerFactory.getLogger(QiniuUtils.class);
    /*
    * 上传文件工具类
    * 把 账号 密码 buket 文件名称  字节数组等抽取到nacos中配置文件，
    *
    * */

    public static void upload2Qiniu(String accessKey,String secretKey,String bucket,byte[] bytes,String fileName) throws RuntimeException{
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        //...其他参数参考类注释 创建用户文件上传的管理者
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = fileName;
        try {
        //获取认证对象
        Auth auth = Auth.create(accessKey, secretKey);
        //拿到认证对象令牌
        String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(bytes, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                LOGGER.error("上传文件到七牛：{}",ex.getMessage());
                try {
                    //异常
                    LOGGER.error(r.bodyString());
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore

                }
                //上传文件失败抛出运行时异常，在自己编写的系统强转成自定义异常
                throw new RuntimeException(r.bodyString());
            }
        }catch (Exception ex) {
            //ignore
            LOGGER.error("上传文件到七牛: {}",ex.getMessage());
            //上传文件失败抛出运行时异常，在自己编写的系统强转成自定义异常
            throw new RuntimeException(ex.getMessage());
        }
    }



    //测试文件上传
    public static  void testUpload() throws IOException {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.huanan());
        //...其他参数参考类注释 创建用户文件上传的管理者
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = "rqIlHHTXp6FqzQ6VARMJRlaSFxYwedMSWlpidKe-";
        String secretKey = "TB91VDYL56pS0pE7OO20QiHasF68BN44aze44U5s";
        String bucket = "shanjupay-m6";
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = UUID.randomUUID().toString()+".png";
        FileInputStream fileInputStream = null;
        try {
            String filePath = "D:\\尚医通\\笔记\\02-分析图\\40-token.png";
            //创建文件输入流 文件输入流进行文件的传输
             fileInputStream = new FileInputStream(filePath);
            //byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
            //使用七牛云提供IOUtils 把本地文件进行转换成字节数组
            byte[] uploadBytes = IOUtils.toByteArray(fileInputStream);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(uploadBytes, key, upToken);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        }catch (UnsupportedEncodingException ex) {
            //ignore
        }
    }

    //测试文件下载 虽然我们是公有空间 但是可以使用私有空间下载文件的API方式进行文件下载
    private static void testDownLoad() throws UnsupportedEncodingException {
        String fileName = "68c1952f-1193-41dc-9d14-15d04a89575d.png";
        String domainOfBucket = "http://r0ttlx8j4.hn-bkt.clouddn.com";
        String encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        String accessKey = "rqIlHHTXp6FqzQ6VARMJRlaSFxYwedMSWlpidKe-";
        String secretKey = "TB91VDYL56pS0pE7OO20QiHasF68BN44aze44U5s";
        Auth auth = Auth.create(accessKey, secretKey);
        long expireInSeconds = 3600;//1小时，可以自定义链接过期时间
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        System.out.println(finalUrl);
    }


    public static void main(String[] args) throws IOException {
        //QiniuUtils.testUpload();
        QiniuUtils.testDownLoad();
    }
}
